﻿/*
Configuration Server
 
Provides a single configuration point for the several instances (development, 
staging, testing, production, etc.) for web sites
 
Includes ideas and code from all over the internet. Specially, stacktrace, msdn, github.
 
Copyright (C) 2014 by Jaime Espinosa <jaimeespinosa60@gmail.com>
 
The MIT License (MIT)

Copyright (c) 2014 jaime espinosa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

  @author Jaime Espinosa <jaimeespinosa60@gmail.com>
  @package configuracion
  @version 0.1
*/

using Configuracion.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;

namespace Configuracion.Controllers
{
    public class SetController : baseController
    {
        [Authorize]
        public ActionResult list(int bundleID = 0)
        {
            ViewBag.Exception = "";
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            if (User.Identity.IsAuthenticated)
                strUserName = User.Identity.Name;

            bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                             .SelectMany(p => p.bundles)
                         select p.ID).ToList<int>();

            if (bundleIDs.Contains(bundleID))
            {
                bundle = (from p in dbContext.Bundles.Include(p => p.Sets)
                          where p.ID == bundleID
                          select p).FirstOrDefault<mdlBundle>();
            }

            return View(bundle);
        }
        [Authorize]
        public JsonResult newSet(int bundleID = 0, string strName = "", string strDescription = "", int intCacheDuration = 0)
        {
            string strError = "";
            string strUserName = "";
            mdlBundle bundle = default(mdlBundle);

            if ((bundleID == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundle = (from p in dbContext.Owners.Include(p => p.bundles)
                                .Include(p => p.bundles.Select(b => b.Sets))
                                .Where(p => p.users.Any(u => u.userName == strUserName))
                                .SelectMany(p => p.bundles)
                          where p.ID == bundleID
                          select p).FirstOrDefault<mdlBundle>();

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Sets == null)
                    bundle.Sets = new List<mdlBundleSet>();

                mdlBundleSet newSet = new mdlBundleSet(strName, strDescription);

                newSet.cacheDuration = intCacheDuration;
                newSet.consumerUserName = "";
                newSet.consumerPassword = "";

                bundle.Sets.Add(newSet);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Set created" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult editSet(int bundleID = 0, int setID = 0, string strName = "", string strDescription = "", int intCacheDuration = 0)
        {
            string strError = "";
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            if ((bundleID == 0) || (setID == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Sets)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Sets == null)
                    return Json(new { error = "Set not found" }, JsonRequestBehavior.AllowGet);

                mdlBundleSet editSet = (from k in bundle.Sets
                                        where k.ID == setID
                                        select k).FirstOrDefault<mdlBundleSet>();

                if (editSet == null)
                    return Json(new { error = "Set not found" }, JsonRequestBehavior.AllowGet);

                // UPDATES Set
                editSet.name = strName;
                editSet.description = strDescription;
                editSet.cacheDuration = intCacheDuration;

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Set updated" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult dropSet(int bundleID = 0, int setID = 0)
        {
            string strError = "";
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            if ((bundleID == 0) || (setID == 0))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Sets)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Sets == null)
                    return Json(new { error = "Set not found" }, JsonRequestBehavior.AllowGet);

                mdlBundleSet removeSet = (from k in bundle.Sets
                                          where k.ID == setID
                                          select k).FirstOrDefault<mdlBundleSet>();

                if (removeSet == null)
                    return Json(new { error = "Set not found" }, JsonRequestBehavior.AllowGet);

                // REMOVE THE Set
                bundle.Sets.Remove(removeSet);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Set removed" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult infoSet(int bundleID = 0, int setID = 0)
        {
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            mdlBundleSet returnSet = default(mdlBundleSet);

            if ((bundleID == 0) || (setID == 0))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Sets)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Sets == null)
                    return Json(new { error = "Set not found" }, JsonRequestBehavior.AllowGet);

                returnSet = (from k in bundle.Sets
                             where k.ID == setID
                             select k).FirstOrDefault<mdlBundleSet>();
                // password should not be available, even hashed one.
                returnSet.consumerPassword = "";

                if (returnSet == null)
                    return Json(new { error = "Set not found" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "Set obtained", data = returnSet }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult SetList(int bundleID = 0)
        {
            string strUserName = "";
            mdlBundle bundle = default(mdlBundle);

            if (bundleID == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                List<int> bundleIDs = default(List<int>);

                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                                 .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Sets)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "List obtained", data = bundle.Sets }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public ActionResult access(int bundleID = 0, int setID = 0)
        {
            string strError = "";
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);
            mdlBundleSet editSet = default(mdlBundleSet);

            if ((bundleID == 0) || (setID == 0))
            {
                throw new Exception("invalid parameters");
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Sets)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    throw new Exception("Bundle not found");

                if (bundle.Sets == null)
                    throw new Exception("Set not found");

                editSet = (from k in bundle.Sets
                           where k.ID == setID
                           select k).FirstOrDefault<mdlBundleSet>();

                if (editSet == null)
                    throw new Exception("Set not found");

                // password should not be available, even hashed one.
                editSet.consumerPassword = "";

                if (Request.Form["tstPost"] != null)
                {
                    // UPDATES Set
                    string consumerUserName = Request.Form["consumerUserName"];
                    string consumerPassword = Request.Form["consumerPassword"];

                    editSet.consumerUserName = consumerUserName;
                    editSet.consumerPassword = HashString(consumerPassword);

                    if (dbContext.GetValidationErrors().Count() > 0)
                    {
                        foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                            foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                                strError += valerror.ErrorMessage.ToString() + "<br/>";

                        throw new Exception("Please verify:" + strError.ToString());
                    }
                    else
                    {
                        dbContext.SaveChanges();
                        return RedirectToAction("list", "set", new { BundleID = bundleID });
                    }
                }

                return View(editSet);
            }
            catch (Exception ex)
            {
                throw new Exception(infoExcepcion(ex));
            }
        }
    }
}